//
//  WJYWKViewController.m
//  NtoccDriverNew
//
//  Created by niyongsheng on 2021/10/12.
//  Copyright © 2021 GCY. All rights reserved.
//
//  万金油H5页面
//  self.urlStr = @"http://0712_ios_getlocation.wechat.tyidian.nucarf.cn/share/ios";

#import "WJYWKViewController.h"
#import <WebKit/WebKit.h>

@interface WJYWKViewController () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@end

@implementation WJYWKViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configLocationManager];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    // 注册js方法
    [configuration.userContentController addScriptMessageHandler:self name:@"openNav"];
    [configuration.userContentController addScriptMessageHandler:self name:@"getLoction"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) configuration:configuration];
    
    //通过JS 调用到userAgent，然后增加一些内容后赋值
    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *_Nullable error) {
        NSString *oldUserAgent = result;
        NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@", oldUserAgent, @"ios_webkit"];
        //        NSString *newUserAgent = [NSString stringWithFormat:@"%@%@", oldUserAgent, @";isApp"];
        webView.customUserAgent = newUserAgent;
    }];
    
    [webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:webView];
    [webView loadRequest:request];
    self.wkWebView = webView;
    [self.view addSubview:self.progressView];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    self.navigationItem.leftItemsSupplementBackButton = YES;
    UIImage *bgImage = [[UIImage imageWithColor:UIColor.whiteColor] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [DCSpeedy changeNavControllerGradientView:self andBgColor:bgImage andTitleColor:[UIColor blackColor]];
}

- (void)refreshAction:(id)sender {
    [self.wkWebView reload];
}

- (void)backButtonTapClick {
    
    if ([self.wkWebView canGoBack]) {
        [self.wkWebView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    self.title = webView.title;
    NSLog(@"网页标题:%@", webView.title);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"错误%@", error);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString * absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSString * scheme = @"testhtml://";
    // JS调用OC
    if ([absoluteString hasPrefix:scheme]) {
        [self jsCallOCMethodWithRequest:navigationAction.request];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

#pragma mark - 拦截scheme并做相应的处理
- (void)jsCallOCMethodWithRequest:(NSURLRequest *)request {
    NSLog(@"URL--%@",request.URL.absoluteString);
    
    NSString * urlString = request.URL.absoluteString;;
    NSString * scheme = @"openNav://";
    if ([urlString hasPrefix:scheme]) {
        
        NSString * subString = [urlString substringFromIndex:scheme.length];
        NSArray * temp = [subString componentsSeparatedByString:@"?"];
        NSString * method = [temp firstObject];
        
        if ([method isEqualToString:@"mapNavigation"]) {
            NSString * string = [temp lastObject];
            NSRange range = [string rangeOfString:@"&"];
            NSString * param1 = [string substringToIndex:range.location];
            NSString * param2 = [string substringFromIndex:range.location + 1];
            NSString * param3 = [string substringFromIndex:range.location + 2];
            
            // 导航弹框
            [self tapNavActionWithAddress:param1 coordinate:(CLLocationCoordinate2D){param2.floatValue, param3.floatValue}];
        }

    }
    
}

#pragma mark - H5 向 Native 发送信息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"js名称:%@", message.name);
    if ([message.name isEqualToString:@"getLoction"]) {
        [self getLocation];
    } else if ([message.name isEqualToString:@"openNav"]) {
        NSDictionary *params = message.body;
        CGFloat lng = [[params objectForKey:@"station_lng"] floatValue];
        CGFloat lat = [[params objectForKey:@"station_lat"] floatValue];
        [self openNav:[params objectForKey:@"station_name"] :(CLLocationCoordinate2D){lat, lng}];
    }
}

#pragma mark - 调用高德一次定位获取位置方法
- (void)getLocation {
    WEAKSELF
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"获取位置失败"];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed) {
                return;
            }
        }
        
        NSLog(@"location:%@", location);
        // 传入当前经纬度
        NSDictionary *param = @{
            @"lng": CJStringWithFormat(@"%f",location.coordinate.longitude),
            @"lat": CJStringWithFormat(@"%f",location.coordinate.latitude)
        };
        // 转为json 字符串
        NSString *paramString = [param jsonStringEncoded];
        NSString *js = [NSString stringWithFormat:@"appGetLocationCallback('',%@)", paramString];
        [weakSelf.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable obj, NSError *_Nullable error) {
            NSLog(@"注入方法%@", error ? @"失败": @"成功");
        }];
    }];
}

#pragma mark - js导航回调
- (void)openNav:(NSString *)location :(CLLocationCoordinate2D)coordinate2D {
    //    CLLocationCoordinate2DMake(39.915352,116.397105);
    [self tapNavActionWithAddress:location coordinate:coordinate2D];
}

#pragma mark - 根据已安装的app和经纬度跳地图导航
- (void)tapNavActionWithAddress:(NSString *)address coordinate:(CLLocationCoordinate2D)coordinate {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择导航" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"苹果自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
        
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *tolocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        
        tolocation.name= address;
        
        [MKMapItem openMapsWithItems:@[currentLocation,tolocation]launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
    }];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        UIAlertAction*action2 = [UIAlertAction actionWithTitle:@"高德地图"style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
            
            NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",coordinate.latitude, coordinate.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlsting] options:@{UIApplicationOpenURLOptionsSourceApplicationKey: @YES} completionHandler:nil];
            
        }];
        
        [alert addAction:action2];
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"百度地图"style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
            NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02", coordinate.latitude, coordinate.longitude, address] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlsting] options:@{UIApplicationOpenURLOptionsSourceApplicationKey: @YES} completionHandler:nil];
            
        }];
        [alert addAction:action3];
        
    }
    
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    
    [alert addAction:action4];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

#pragma -mark 配置高德导航
- (void)configLocationManager {
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout = 10;
    //   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
}

#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        // 加载完成
        if (self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.25f animations:^{
                self.progressView.alpha = 0.0f;
                self.progressView.progress = 0.0f;
            }];
        } else {
            self.progressView.alpha = 1.0f;
        }
    }
}

#pragma mark 进度条
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
        _progressView.progressViewStyle = UIProgressViewStyleBar;
        _progressView.tintColor = UIColor.greenColor;
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
